﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using Yqd.Controllers.Filter;
using Adp.Common;
using System.Linq;
using System;
using Yqd.Core;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Newtonsoft.Json.Linq;
using Yqd.Enm;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxExactSuperviseController : Controller
    {
        YqdContext ctx;

        public WxExactSuperviseController(YqdContext ctx)
        {
            this.ctx = ctx;
        }
        [User]
        public ActionResult GetList()
        {
            var TaskID = Form.GetLong("TaskID");
            var Guid = Form.GetString("GUID");
            var Status = Form.GetInt("Status", 0);
            var r = ctx.Yqd_ExactSupervise.Where(it => it.TaskID == TaskID);
            if (Guid.HasValue()) r = r.Where(it => it.GUID == Guid);
            var assign = ctx.Yqd_Assign.Where(it => it.TaskID == TaskID && it.ItemType == 事项类型.精准督查).ToList();
            var l = WxUser.LogonInfo;
            var DeptRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门联络员);
            var MsRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员);
            var platform = Form.GetInt("platform", 1);
            if (DeptRole && platform == 2)
            {
                assign = assign.Where(it => it.LeadUnit == l.UnitCode).ToList();
            }
            var plan = ctx.Yqd_JobPlan.Where(it => it.CheckStatus != 审核状态.退回 && it.ItemType == 事项类型.精准督查).ToList();
            var bplan = ctx.Yqd_JobPlan.Where(it => it.CheckStatus == 审核状态.退回 && it.ItemType == 事项类型.精准督查).ToList();
            var progress = ctx.Yqd_PlanProgress.Where(it => it.CheckStatus != 审核状态.退回 && it.ItemType == 事项类型.精准督查).ToList();
            var bprogress = ctx.Yqd_PlanProgress.Where(it => it.CheckStatus == 审核状态.退回 && it.ItemType == 事项类型.精准督查).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            if (Status == 60) //60未完结
            {
                r = r.Where(it => it.Status == 办理情况.未回复 || it.Status == 办理情况.已回复 || it.Status == 办理情况.已滞后);
            }
            if (Status == 70) //70已交办
            {
                r = r.Where(it => it.Status > 办理情况.待交办);
            }
            if (Status == 80) //待办任务
            {
                r = r.Where(it => it.IsDeal);
            }
            switch ((办理情况)Status)
            {
                case 办理情况.待交办:
                    r = r.Where(it => it.Status == 办理情况.待交办);
                    break;
                case 办理情况.未回复:
                    r = r.Where(it => it.Status == 办理情况.未回复);
                    break;
                case 办理情况.已回复:
                    r = r.Where(it => it.Status == 办理情况.已回复 || it.Status == 办理情况.已完结);
                    break;
                case 办理情况.已完结:
                    r = r.Where(it => it.Status == 办理情况.已完结);
                    break;
                case 办理情况.已滞后:
                    r = r.Where(it => it.Status == 办理情况.已滞后);
                    break;
            }
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            var totalcount = r.Count();
            var data = r.ToList().Select(it => new
            {
                it.SuperviseID,
                it.LightSpot,
                it.Problem,
                it.IsLb,
                Photos = !string.IsNullOrWhiteSpace(it.Photos) ? JArray.Parse(it.Photos) : new JArray(),
                Status = it.Status.ToString(),
                AssignLimit = it.Instime.AddDays(7).ToString("yyyy-MM-dd"),
                ShowAssign = !assign.Any(s => s.ItemID == it.SuperviseID) || !plan.Any(m => m.ItemID == it.SuperviseID),
                Assign = assign.Where(s => s.ItemID == it.SuperviseID).Select(n => new
                {
                    n.AssignID,
                    Item = n.Item ?? "",
                    n.LeadUnit,
                    ShowHistory = bplan.Any(b => b.AssignID == n.AssignID),
                    Dept = dept.FirstOrDefault(d => d.UnitCode == n.LeadUnit)?.Name,
                    AssignLimit = n.AssignLimit.ToString("yyyy.MM.dd"),
                    AssignTime = n.Instime.ToString("yyyy.MM.dd"),
                    AssignMan = user.FirstOrDefault(m => m.EmployeeCode == n.EmployeeCode)?.Name,
                    IsCheck = plan.Any(m => m.AssignID == n.AssignID && m.CheckStatus == Enm.审核状态.待审),
                    IsChecked = plan.Any(m => m.AssignID == n.AssignID && m.CheckStatus == Enm.审核状态.同意),
                    ShowAgree = progress.Any(b => b.AssignID == n.AssignID && b.CheckStatus == 审核状态.待审),
                    Plan = plan.Where(m => m.AssignID == n.AssignID).ToList().Select(s => new
                    {
                        s.PlanID,
                        Measure = s.Measure ?? "",
                        s.Leader,
                        s.Linkman,
                        ShowHistory = bprogress.Any(b => b.PlanID == s.PlanID),
                        IsChecked = s.CheckStatus == Enm.审核状态.同意,
                        Status = Enum.GetName(typeof(Enm.任务计划完成状态), s.Status),
                        PlanCompleteTime = s.PlanCompleteTime != null ? s.PlanCompleteTime.ToString("yyyy.MM.dd") : "",
                        Progress = progress.Where(b => b.PlanID == s.PlanID).OrderByDescending(c => c.Instime).ToList().Select(m => new
                        {
                            m.ProgressID,
                            IsCheck = m.CheckStatus == Enm.审核状态.待审,
                            IsDeal = m.PlanStatus == Enm.任务计划办理情况.申请延期,
                            PlanStatus = m.PlanStatus == 0 ? "" : m.PlanStatus.ToString(),
                            PlanResult = m.PlanResult ?? "",
                            DelayReason = m.DelayReason ?? "",
                            DelayTime = m.DelayTime != null ? m.DelayTime.ToString("yyyy.MM.dd") : ""
                        })
                    })
                })
            });
            return this.ToJson(new
            {
                success = true,
                totalcount,
                DeptRole,
                MsRole,
                task.TaskName,
                task.LeaderUnitCode,
                data = data.Where(it => !it.IsLb),
                lbdata = data.Where(it => it.IsLb)
            });
        }

        [User]
        public ActionResult GetWeeklyPaper()
        {
            var sdate = Form.GetDateTime("sdate",GetWeekFirstDay());
            var edate = Form.GetDateTime("edate", GetWeekLastDay());
            var tasks = ctx.Yqd_Task.Select(it => new { it.TaskID, it.TaskName }).ToList();
            var ed = edate.AddDays(1);
            var assigns = ctx.Yqd_Assign.Where(it =>it.ItemType == 事项类型.精准督查 && it.Instime >= sdate && it.Instime < ed).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.AssignLimit, it.Instime }).ToList();
            var unit = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name });
            var fb = ctx.Yqd_JobPlan.Where(it=>it.CheckStatus == 审核状态.同意).Select(it => new { it.AssignID, it.Measure }).ToList();
            var sIDs = assigns.Select(it => it.ItemID).ToArray();
            var supervise = ctx.Yqd_ExactSupervise.Where(it => sIDs.Contains(it.SuperviseID));
            var data = new List<object>();
            foreach(var s in supervise)
            {
                var a = assigns.FirstOrDefault(it => it.ItemID == s.SuperviseID);
                if (a != null)
                {
                    data.Add(new
                    {
                        TaslName = tasks.FirstOrDefault(it => it.TaskID == s.TaskID)?.TaskName,
                        LeadUnit = unit.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name,
                        s.Problem,
                        Feedback = string.Join("<br/>",fb.Where(it => it.AssignID == a.AssignID).Select(it=>it.Measure)),
                        AssignTime = a.Instime.ToString("yyyy年MM月dd日"),
                        AssignLimit = a.AssignLimit.ToString("yyyy年MM月dd日")
                    });
                }
            }
            return this.ToJson(new
            {
                success = true,
                sdate = sdate.ToString("yyyy-MM-dd"),
                edate = edate.ToString("yyyy-MM-dd"),
                totalcount = data.Count(),
                data
            });
        }

        /// <summary>
        /// 得到本周第一天
        /// </summary>
        public DateTime GetWeekFirstDay()
        {
            var dt = DateTime.Now.Date;
            int weeknow = Convert.ToInt32(dt.DayOfWeek);
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;
            string FirstDay = dt.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>
        /// 得到本周最后一天(以星期天为最后一天)
        /// </summary>
        public DateTime GetWeekLastDay()
        {
            var dt = DateTime.Now.Date;
            int weeknow = Convert.ToInt32(dt.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);
            string LastDay = dt.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }

        [User]
        public ActionResult OutImport()
        {
            try
            {
                var sdate = Form.GetDateTime("sdate", GetWeekFirstDay());
                var edate = Form.GetDateTime("edate", GetWeekLastDay());
                var tasks = ctx.Yqd_Task.Select(it => new { it.TaskID, it.TaskName }).ToList();
                var ed = edate.AddDays(1);
                var assigns = ctx.Yqd_Assign.Where(it =>it.ItemType == 事项类型.精准督查 && it.Instime >= sdate && it.Instime < ed).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.AssignLimit, it.Instime }).ToList();
                var dt = sdate.ToString("yyyy年M月d日");
                if (sdate.Year == edate.Year)
                    dt += edate.ToString("-M月d日");
                else
                    dt += edate.ToString("-yyyy年M月d日");
                var unit = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name });
                var fb = ctx.Yqd_JobPlan.Where(it => it.CheckStatus == 审核状态.同意).Select(it => new { it.AssignID, it.Measure }).ToList();
                var sIDs = assigns.Select(it => it.ItemID).ToArray();
                var supervise = ctx.Yqd_ExactSupervise.Where(it => sIDs.Contains(it.SuperviseID));
                var data = new List<dynamic>();
                foreach (var s in supervise)
                {
                    var a = assigns.FirstOrDefault(it => it.ItemID == s.SuperviseID);
                    if (a != null)
                    {
                        data.Add(new
                        {
                            tasks.FirstOrDefault(it => it.TaskID == s.TaskID)?.TaskName,
                            LeadUnit = unit.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name,
                            s.Problem,
                            Feedback = string.Join("\n", fb.Where(it => it.AssignID == a.AssignID).Select(it => it.Measure)),
                            AssignTime = a.Instime.ToString("yyyy年MM月dd日"),
                            AssignLimit = a.AssignLimit.ToString("yyyy年MM月dd日")
                        });
                    }
                }
                const string filename = "督查周报表.xlsx";
                var path = Config.Yqdpath("/sys/xls/");
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                FileInfo file = new FileInfo(path + filename);
                if (file.Exists) file.Delete();
                var title = new[] { "任务名称", "责任单位", "督查问题", "办理情况", "交办时间", "办理时限", "备注" };
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("督查周报");

                    worksheet.Cells[1, 1].Style.Font.Name = "宋体";
                    worksheet.Cells[1, 1].Style.Font.Bold = true;
                    worksheet.Cells[1, 1].Style.Font.Size = 16;
                    worksheet.Cells.Style.ShrinkToFit = true;
                    worksheet.Row(1).Height = 80;
                    worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    worksheet.Cells[1, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    worksheet.Cells[1, 1].Value = "督查周报\n" + dt;
                    worksheet.Cells[1, 1, 1, 7].Merge = true;
                    int index = 1;
                    foreach (string t in title)
                    {
                        worksheet.Cells[2, index].Style.Font.Name = "宋体";
                        worksheet.Cells[2, index].Style.Font.Bold = true;
                        worksheet.Cells[2, index].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(2).Height = 30;
                        worksheet.Column(index).Width = 20;
                        worksheet.Row(2).CustomHeight = true;
                        worksheet.Cells[2, index].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[2, index].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[2, index].Value = t;
                        index++;
                    }
                    index = 3;
                    foreach (var d in data)
                    {
                        worksheet.Cells[index, 1].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 1].Style.Font.Bold = false;
                        worksheet.Cells[index, 1].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(1).Width = 60;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 1].Value = d.TaskName;
                        worksheet.Cells[index, 2].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 2].Style.Font.Bold = false;
                        worksheet.Cells[index, 2].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(2).Width = 20;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 2].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 2].Value = d.LeadUnit;
                        worksheet.Cells[index, 3].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 3].Style.Font.Bold = false;
                        worksheet.Cells[index, 3].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(3).Width = 60;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 3].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 3].Value = d.Problem;
                        worksheet.Cells[index, 4].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 4].Style.Font.Bold = false;
                        worksheet.Cells[index, 4].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(4).Width = 60;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 4].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 4].Value = d.Feedback;
                        worksheet.Cells[index, 5].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 5].Style.Font.Bold = false;
                        worksheet.Cells[index, 5].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(5).Width = 20;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 5].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 5].Value = d.AssignTime;
                        worksheet.Cells[index, 6].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 6].Style.Font.Bold = false;
                        worksheet.Cells[index, 6].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(6).Width = 20;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 6].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 6].Value = d.AssignLimit;
                        worksheet.Cells[index, 7].Style.Font.Name = "宋体";
                        worksheet.Cells[index, 7].Style.Font.Bold = false;
                        worksheet.Cells[index, 7].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(index).Height = 30;
                        worksheet.Column(7).Width = 30;
                        worksheet.Row(index).CustomHeight = true;
                        worksheet.Cells[index, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[index, 7].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[index, 7].Value = "";
                        index++;
                    }
                    package.Save();
                    package.Dispose();
                    return Json(new
                    {
                        success = true,
                        filepath = "/sys/xls/" + filename
                    });
                }
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    ex.Message
                });
            }
        }

        /// <summary>
        /// 添加督查取证
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add()
        {
            var TaskID = Form.GetLong("TaskID");
            var IsLb = Form.GetBool("IsLb", false);
            var datas = Form.GetString("datas").ToJArray();
            var guid = Guid.NewGuid().ToString();
            foreach (var info in datas)
            {
                ctx.Yqd_ExactSupervise.Add(new Yqd_ExactSupervise
                {
                    TaskID = TaskID,
                    LightSpot = info["LightSpot"].ToString(),
                    Problem = info["Problem"].ToString(),
                    Photos = info["Photos"]?.ToString() ?? "",
                    Instime = DateTime.Now,
                    Status = 办理情况.待交办,
                    IsLb = IsLb,
                    IsDeal = false,
                    GUID = guid,
                    EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                    UnitCode = WxUser.LogonInfo.UnitCode
                });
            }
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                TaskLogService.AddLog(TaskID, "督查取证了");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_ExactSupervise where SuperviseID={0};", SuperviseID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}